package com.glory.hikvisionmobile.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.hikvisionmobile.R;
import com.glory.hikvisionmobile.adapter.DBCarrierAdapter;
import com.glory.hikvisionmobile.base.BaseActivity;
import com.glory.hikvisionmobile.base.Constant;
import com.glory.hikvisionmobile.bean.TrackOut.TrackOutLoadBean;
import com.glory.hikvisionmobile.bean.TrackOut.TrackOutSubmitBean;
import com.glory.hikvisionmobile.bean.TrackOut.XSortingAndBoundsBean;
import com.glory.hikvisionmobile.bean.net.BaseResponseBean;
import com.glory.hikvisionmobile.customView.HikLabelEditText;
import com.glory.hikvisionmobile.customView.HikLabelTextView;
import com.glory.hikvisionmobile.utils.DialogUtils;
import com.glory.hikvisionmobile.utils.EditTextEnterUtils;
import com.glory.hikvisionmobile.utils.NetUtils;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StringUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_ToastUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_Utils;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class Work_VacuumSealingTrackOutActivity extends BaseActivity {

    private static final int CODE = 0x000001;

    @BindView(R.id.lbLot)
    HikLabelTextView lbLot;
    @BindView(R.id.lbMainWork)
    HikLabelTextView lbMainWork;
    @BindView(R.id.lbNum)
    HikLabelTextView lbNum;
    @BindView(R.id.lbCurrentStep)
    HikLabelTextView lbCurrentStep;
    @BindView(R.id.lbDBCarrier)
    HikLabelEditText lbDBCarrier;
    @BindView(R.id.lbRemarks)
    HikLabelEditText lbRemarks;
    @BindView(R.id.rvSortingList)
    RecyclerView rvSortingList;
    @BindView(R.id.bottom_tv1)
    TextView bottomTv1;
    @BindView(R.id.bottom_tv2)
    TextView bottomTv2;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    private String lotType;
    private String lotNum;
    private DBCarrierAdapter dbCarrierAdapter;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_vacuum_sealing_track_out;
    }

    @Override
    protected void initView() {
        Bundle bundle = getIntent().getExtras();
        lotType = bundle.getString("lotType");
        lotNum = bundle.getString("lotNum");
        lbLot.getLabelContext().setText(lotNum);

        rvSortingList.setLayoutManager(new LinearLayoutManager(Work_VacuumSealingTrackOutActivity.this));
        rvSortingList.setItemAnimator(new DefaultItemAnimator());
        rvSortingList.addItemDecoration(new DividerItemDecoration(Work_VacuumSealingTrackOutActivity.this, 1));
        dbCarrierAdapter = new DBCarrierAdapter(null);
        dbCarrierAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        dbCarrierAdapter.isFirstOnly(true);
        rvSortingList.setAdapter(dbCarrierAdapter);

        EditTextEnterUtils.initPdaEditText(lbDBCarrier.getLabelContext(), false, text -> {
            loadData(lotNum, text);
        });
    }


    @Override
    protected void initData() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        String dbCarrier = lbDBCarrier.getLabelContext().getText().toString();
        loadData(lotNum, TextUtils.isEmpty(dbCarrier) ? null : dbCarrier);
    }

    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        freeUI_titleView.setTitle("160封焊待出站");
        return new FreeUI_AddViewEntity("header", llMain);
    }

    @OnClick({R.id.bottom_tv1})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bottom_tv1:
                initPermission("TrackOut", this, new ActionControlListener() {
                    @Override
                    public void onControlChangeListener() {
                        submit("Comment","HIK.PdaVacuumSealingTrackOut");
                    }
                });
                break;
        }
    }

    private void loadData(String lotId, String carrierId) {
        JsonObject map = new JsonObject();
        if (lotId != null) {
            map.addProperty("lotId", lotId);
        }
        if (carrierId != null) {
            map.addProperty("dbCarrierId", carrierId);
        }
        NetUtils.requestDara("HIK.PdaVacuumSealingTrackOutLoad",this,map,new FreeUI_DialogEntityCallBack<BaseResponseBean<TrackOutLoadBean>>(
                new TypeToken<BaseResponseBean<TrackOutLoadBean>>() {
                }.getType(), getSupportFragmentManager(), this){

            @Override
            public void onSuccess(Response<BaseResponseBean<TrackOutLoadBean>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(),true,getSupportFragmentManager())) {
                    TrackOutLoadBean trackOutLoadBean = response.body().getBody();
                    List<XSortingAndBoundsBean> xSortingAndBoundsBeans = trackOutLoadBean.getxDieSortings();
                    dbCarrierAdapter.setNewData(xSortingAndBoundsBeans);
                    lbCurrentStep.getLabelContext().setText(trackOutLoadBean.getCurrentStepDesc());
                    lbMainWork.getLabelContext().setText(trackOutLoadBean.getMainEquipments());
                    lbNum.getLabelContext().setText(String.valueOf(trackOutLoadBean.getMainQty() ));

                    if ("NONE".equals(trackOutLoadBean.getEdcState()) || "N".equals(trackOutLoadBean.getEdcState())) {
                        bottomTv2.setEnabled(false);
                        bottomTv1.setEnabled(true);
                    } else {
                        bottomTv2.setEnabled(true);
                        bottomTv1.setEnabled(false);
                        bottomTv2.setOnClickListener(v -> {
                            if (actionControl("Work_SPCDataCollectActivity", "PDAWorkFragment", "无SPC数据采集权限"))
                                return;
                            Bundle b = new Bundle();
                            b.putString("lot", lotNum);
                            b.putString("paramsName", trackOutLoadBean.getParameterSet());
                            b.putString("mainDevice", trackOutLoadBean.getMainEquipments());
                            b.putString("partName",trackOutLoadBean.getPartName());
                            b.putString("partDesc",trackOutLoadBean.getPartDesc());
                            b.putString("itemDevice", trackOutLoadBean.getSubEquipments() == null ? "" : trackOutLoadBean.getSubEquipments());
                            FreeApi_Utils.skipWithExtraIntent("header", b, Work_VacuumSealingTrackOutActivity.this, Work_SPCDataCollectActivity.class);
                        });
                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<TrackOutLoadBean>> response) {
                super.onError(response);
                loadError(response.getException(),"HIK.PdaVacuumSealingTrackOutLoad");
            }
        });
    }

    private void submit(String actionType, String messageName) {
        if (dbCarrierAdapter.getJsonData() == null) {
            FreeApi_ToastUtils.showFreeToast("未绑定载具", this, false, Toast.LENGTH_SHORT);
            return;
        }
        DialogUtils.showLoginDialog(this, Constant.CURRENT_USER, new DialogUtils.signCallback() {
            @Override
            public void onSignSuccess() {
                JsonObject map = new JsonObject();
                map.addProperty("lotId",lotNum);
                map.addProperty("actionType","Check");
                map.addProperty("comment",lbRemarks.getLabelContext().getText().toString().trim());
                map.addProperty("operationType",actionType);
                map.addProperty("mainEquipmentId",lbMainWork.getLabelContext().getText().toString());
                JsonObject jsonObject = new JsonObject();
                jsonObject.add("XPdaDieSorting", dbCarrierAdapter.getJsonData());
                map.add("xDieSortings", jsonObject);
                NetUtils.requestDara(messageName,this,map,new FreeUI_DialogEntityCallBack<BaseResponseBean<TrackOutSubmitBean>>(
                        new TypeToken<BaseResponseBean<TrackOutSubmitBean>>() {
                        }.getType(), getSupportFragmentManager(), this){

                    @Override
                    public void onSuccess(Response<BaseResponseBean<TrackOutSubmitBean>> response) {
                        super.onSuccess(response);
                        if (response.body().isSuccess(getApplicationContext(),false,getSupportFragmentManager())) {
                            if (actionType.equals("Comment")){
                                String nextStepName = response.body().getBody().getNextStepDesc();
                                if (FreeApi_StringUtils.isEmpty(nextStepName)){
                                    showConfirmDialog(Work_VacuumSealingTrackOutActivity.this,"出站成功，没有下一道工序");
                                }else {
                                    showConfirmDialog(Work_VacuumSealingTrackOutActivity.this,"出站成功，下一道工序是:" + nextStepName);
                                }

                            }else {
                                showConfirmDialog(Work_VacuumSealingTrackOutActivity.this,"退站成功");
                            }
                        }
                    }

                    @Override
                    public void onError(Response<BaseResponseBean<TrackOutSubmitBean>> response) {
                        super.onError(response);
                        loadError(response.getException(),messageName);

                    }
                });

            }
        },getSupportFragmentManager());
    }
}
